<template>
  <div class="objectTree-attr">
    <div class="base-row-item row-1">
      <div class="main-text-tran-50">图层选择</div>
      <div
        v-if="select_data_tree"
        class="main-mas-input-simple main-mas-input-simple-input"
      >
        <div class="mas-basic-layout">
          <select
            @change="selectchange"
            v-model="selectvalue"
            class="main-mas-basis-select"
          >
            <option value=""><span> -</span></option>
            <option
              v-for="item in select_data_tree.infotree.filter(
                (i) => i.type == 'EPT_Scene'
              )"
              :value="item.iD"
            >
              <span> {{ item.name }} </span>
            </option>
          </select>
        </div>
      </div>
    </div>
    <el-upload
      ref="upload"
      class="upload"
      action="#"
      accept=".xlsx,.xls"
      multiple
      :auto-upload="false"
      :withCredentials="false"
      :on-change="loadFile"
      :on-remove="handleRemove"
      :show-file-list="true"
      :file-list="fileList"
    >
      <span class="upload_span">选择文件</span>

      <div slot="tip" class="el-upload__tip">【注意】只能上传xls/xlsx文件</div>
      <!-- <div slot="tip" class="el-upload__tip">{{ fileList[0].name }}</div> -->
    </el-upload>
  </div>
</template>

<script>
import store from "@/js/store/state.js";
import JQuery from "jquery";
import history from "@/js/main/history.js";

import * as XLSX from "xlsx";
export default {
  data() {
    return {
      JQuery: JQuery,
      history: history,
      store: store,
      currentElementList: store.getCurrentElementList(),
      imports_show: false,

      fileList: [],
      // tilelayer: null,
      select_data_tree: null,
      selectvalue: null,
    };
  },
  components: {},
  mounted() {
    this.$nextTick(async () => {
      this.reset();
      this.fileList = this.currentElementList[0].data.fileList;
      this.select_data_tree = await __g.infoTree.get();
      // if (__g) {
      // } else {
      // this.$message.error("请先连接");
      // }

      // 如果有图层id数据，则进行回显
      if (this.currentElementList[0].data.tilelayerid) {
        this.selectvalue = this.currentElementList[0].data.tilelayerid;
      }
    });
  },
  methods: {
    selectchange(e) {
      // this.currentElementList[0].data.tilelayerId = selectvalue;
      this.currentElementList[0].data.tilelayerid = this.selectvalue;
    },

    imports() {
      this.imports_show = !this.imports_show;
    },

    loadFile(file, fileList) {
      // alert(11);
      console.log("[ fileList ] >", fileList);
      if (fileList.length > 1) {
        this.$message.error("只能上传一个文件,请先删除。");
        fileList.length = 1;
        return;
      }
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["xls", "xlsx"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是 xls、xlsx格式");
        this.$refs.upload.clearFiles(); //清空已上传的文件列表（该方法不支持在 before-upload 中调用）
        return false;
      }

      this.upload_file = fileList[0].raw;
      const reader = new FileReader();
      reader.readAsBinaryString(this.upload_file);
      reader.onload = (ev) => {
        try {
          const f = ev.target.result;
          const workbook = XLSX.read(f, { type: "binary" });
          const result = [];
          workbook.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]), // 生成JSON表格内容
            });
          });
          //至此，将拿到excel工作簿中的数据，下面就可以自己操作了
          //........
          let test = [];
          result.forEach((res, index) => {
            test[index] = res.sheet.map((item, index) => {
              let time = null;
              let time1 = null;
              let time2 = null;
              let time3 = null;
              // excel导出json格式数据中有关时间的转换（因为导出json的时间格式为数字了，所以需要转换）
              if (typeof item["计划开始时间"] === "number") {
                time = new Date(
                  1900,
                  0,
                  item["计划开始时间"] - 1
                ).toLocaleDateString();
              }
              if (typeof item["计划完成时间"] === "number") {
                time1 = new Date(
                  1900,
                  0,
                  item["计划完成时间"] - 1
                ).toLocaleDateString();
              }
              if (typeof item["实际开始时间"] === "number") {
                time2 = new Date(
                  1900,
                  0,
                  item["实际开始时间"] - 1
                ).toLocaleDateString();
              }
              if (typeof item["实际完成时间"] === "number") {
                time3 = new Date(
                  1900,
                  0,
                  item["实际完成时间"] - 1
                ).toLocaleDateString();
              }
              return {
                父节点编码: item["父节点编码"] ?? null,
                构件Id: item["构件Id"] ?? null,
                编码: item["编码"],
                编码名称: item["编码名称"],
                计划开始时间: time,
                计划完成时间: time1,
                实际开始时间: time2,
                实际完成时间: time3,
              };
            });
          });
          if (test.length == 1) {
            test = test.flat();
          }
          this.setData(test);
          // this.reset();
        } catch (e) {
          console.log(e);
          return false;
        }
      };

      // 文件添加处理完毕后把名称添加到文件列表
      this.fileList = [
        {
          name: file.name,
        },
      ];
    },
    // 删除文件列表中的内容
    handleRemove(file, fileList) {
      this.currentElementList[0].data.treedata = []; //清空储存的甘特图数据
      this.fileList = []; //清空文件列表
      this.currentElementList[0].data.fileList = []; //清空储存的文件列表数据
    },
    beforeupload(file) {
      console.log("[ file ] >", file);
    },
    // 因为甘特图插件免费版只支持同时展示一个甘特图 所以预览后需要进行初始化操作
    reset() {
      this.currentElementList[0].data.reset = "";
      this.currentElementList[0].data.reset = true;
    },
    //设置数据
    setData(data) {
      this.currentElementList[0].data.treedata = data; //储存的是处理后的甘特图数据
      this.currentElementList[0].data.fileList = this.fileList; //文件列表
      // console.log(data, "data");
    },
  },
};
</script>

<style scoped lang="scss">
$background: #ffffff0f;
.upload {
  margin: 20px 0;
}
.upload_span {
  color: aqua;
}
</style>
